package com.swotxu.oldwebproject.session.http;

import com.swotxu.oldwebproject.redis.RedisManager;
import com.swotxu.oldwebproject.redis.connection.IRedisConnection;
import com.swotxu.oldwebproject.session.RedisSessionRepository;
import com.swotxu.oldwebproject.session.utils.RedisSessionUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

/**
 * @Date: 2021/3/24 0024 16:31
 * @Author: swotxu
 */
public class RedisSessionRequestWrapper extends HttpServletRequestWrapper {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisSessionRequestWrapper.class);
    private IRedisConnection connection = RedisManager.getIRedisConnection();
    private RedisSessionRepository repository = new RedisSessionRepository(connection);

    private HttpServletRequest request;
    private HttpSession session;

    private String token;

    public RedisSessionRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;

        Cookie[] cookies = request.getCookies();
        String cookieSessionId = null;
        if (ArrayUtils.isNotEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(RedisSessionUtil.SESSION_TOKEN)) {
                    String cookieValue = cookie.getValue();
                    String sessionKey = RedisSessionUtil.getSessionKey(cookieValue);
                    if (connection.exists(sessionKey)) {
                        cookieSessionId = cookieValue;
                        break;
                    }
                }
            }
        }
        this.token = cookieSessionId == null? RedisSessionUtil.generateSessionId() : cookieSessionId;
    }

    @Override
    public HttpSession getSession(boolean create) {
        if (session != null && session.isNew()){
            session = null;
            token = null;
        }
        if (token == null) {
            token = RedisSessionUtil.generateSessionId();
        }
        if (session == null) {
            session = repository.getSession(token, request.getSession().getServletContext(), create);
        }
        return session;
    }

    @Override
    public HttpSession getSession() {
        return getSession(true);
    }

    @Override
    public String getRequestedSessionId() {
        return token;
    }

}
